<template>
  <div class="device-pricing-form">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">{{ title }}</span>
          <div class="buttons">
            <el-button type="primary" @click="submitForm" :loading="submitLoading" v-if="!isViewMode">
              <el-icon><Check /></el-icon>提交
            </el-button>
            <el-button @click="goBack">
              <el-icon><Back /></el-icon>返回
            </el-button>
          </div>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="right" :disabled="isViewMode">
        <!-- 基本信息 -->
        <el-card class="base-info-card" shadow="never">
          <template #header>
            <div class="form-section-header">
              <el-icon><Document /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectId">
                <el-select v-model="form.projectId" placeholder="请选择设备类别" clearable filterable class="full-width">
                  <el-option 
                    v-for="item in projectList" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备类别" prop="type">
                <el-select v-model="form.type" placeholder="请选择设备类别" clearable filterable class="full-width">
                  <el-option 
                    v-for="item in typeOptions" 
                    :key="item.dictLabel" 
                    :label="item.dictLabel" 
                    :value="item.dictLabel" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input 
                  v-model="form.remark" 
                  type="textarea" 
                  :rows="3" 
                  placeholder="请输入备注信息"
                  class="full-width"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 设备核价明细 -->
        <el-card class="device-details-card" shadow="never">
          <template #header>
            <div class="form-section-header">
              <el-icon><List /></el-icon>
              <span>设备核价明细</span>
            </div>
          </template>

          <!-- 只有当类型为堆垛机或非标堆垛机时才显示表格 -->
          <div v-if="form.type === '堆垛机' || form.type === '非标堆垛机'">
            <!-- 第一个表格：规格参数表 -->
            <h3 class="table-title">规格参数表</h3>
            <el-table :data="specsTableData" border class="device-details-table">
              <el-table-column prop="name" label="名称" min-width="150" align="center" />
              <el-table-column prop="unit" label="单位" width="80" align="center" />
              <el-table-column prop="defaultValue" label="数值(满载)" width="150" align="center">
                <template #default="scope">
                  <el-select
                    v-if="scope.row.name === '货叉类型'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择货叉类型"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in forkTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '通讯方式'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择通讯方式"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in commTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '定位方式'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择定位方式"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in positionTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === 'PLC'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择PLC"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in plcTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '变频器'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择变频器"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in inverterTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '光电开关'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择光电开关"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in photoelectricTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '地面站数量'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择地面站数量"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in stationNumOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '滑触线安装方式'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择滑触线安装方式"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in slideLineInstallOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '能效等级要求'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择能效等级"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in motorEfficiencyOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '当前钢材价格'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择当前钢材价格"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in steelPriceOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-input
                                          v-else
                      v-model="scope.row.defaultValue"
                      :disabled="shouldDisableField(scope.row.name)"
                      :style="{backgroundColor: scope.row.color || 'transparent'}"
                      placeholder="请输入数值(满载)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="price" label="价格（元）" width="150" align="center">
                <template #default="scope">
                  <el-input-number 
                    v-if="!shouldDisableField(scope.row.name + '_price')"
                    v-model="scope.row.price" 
                    :precision="scope.row.precision || 0" 
                    :step="1" 
                    :min="0" 
                    controls-position="right" 
                    style="width: 120px"
                    @change="updateSummarizedData"
                  />
                  <span v-else>{{ scope.row.price }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="150" align="center">
                <template #default="scope">
                  <el-input
                    v-if="!shouldDisableField(scope.row.name + '_remark')"
                    v-model="scope.row.remark"
                    placeholder="请输入备注"
                  />
                  <span v-else>{{ scope.row.remark }}</span>
                </template>
              </el-table-column>
            </el-table>

            <!-- 第二个表格：分项单价表 -->
            <h3 class="table-title pricing-title">分项单价表</h3>
            <el-table :data="pricingTableData" border class="device-details-table pricing-table">
              <el-table-column prop="name" label="名称" min-width="150" align="center" />
              <el-table-column prop="unit" label="单位" width="80" align="center" />
              <el-table-column prop="defaultValue" label="数值(满载)" width="150" align="center">
                <template #default="scope">
                  <el-select
                    v-if="scope.row.name === '行走电机'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择行走电机"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in walkMotorOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '提升电机'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择提升电机"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in liftMotorOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '货叉'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择货叉"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in forkOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '使用环境'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择使用环境"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in envOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '轨道类型'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择轨道类型"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in railTypeOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '单机监控'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择单机监控"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in monitorOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '巷道激光雷达'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择巷道激光雷达"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in lidarOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '铠甲/灭火器'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择铠甲/灭火器"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in armorOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '金属粉尘管控'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择金属粉尘管控"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in dustOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-select
                    v-else-if="scope.row.name === '滑触线'"
                                          v-model="scope.row.defaultValue"
                      placeholder="请选择滑触线"
                      :disabled="shouldDisableField(scope.row.name)"
                      class="full-width"
                      clearable
                  >
                    <el-option
                      v-for="item in slideLineOptions"
                      :key="item.dictLabel"
                      :label="item.dictLabel"
                      :value="item.dictLabel"
                    />
                  </el-select>
                  <el-input
                                          v-else
                      v-model="scope.row.defaultValue"
                      :disabled="shouldDisableField(scope.row.name)"
                      :style="{backgroundColor: scope.row.color || 'transparent'}"
                      placeholder="请输入数值(满载)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="price" label="价格（元）" width="150" align="center">
                                  <template #default="scope">
                    <el-input-number
                     v-if="!shouldDisableField(scope.row.name + '_price')"
                     v-model="scope.row.price"
                     :precision="scope.row.precision || 0"
                     :step="1"
                     :min="0"
                     controls-position="right"
                     style="width: 120px"
                    @change="updateSummarizedData"
                  />
                  <span v-else>{{ scope.row.price }}</span>
                  </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="150" align="center">
                                  <template #default="scope">
                    <el-input
                     v-if="scope.row.name === '货叉' && !shouldDisableField(scope.row.name + '_remark')"
                     v-model="scope.row.remark"
                     placeholder="请输入备注"
                     @change="onForkRemarkChange"
                    />
                   <el-input
                     v-else-if="scope.row.name !== '货叉' && !shouldDisableField(scope.row.name + '_remark')"
                     v-model="scope.row.remark"
                     placeholder="请输入备注"
                   />
                   <span v-else>{{ scope.row.remark }}</span>
                  </template>
              </el-table-column>
            </el-table>
            
            <!-- 操作按钮 -->
            <div class="table-actions">
              <el-button type="primary" @click="calculatePricing" :loading="calculateLoading" v-if="!isViewMode">
                <el-icon><RefreshRight /></el-icon> 更新计算
              </el-button>
              <el-button type="success" @click="saveTableData" :loading="saveLoading" v-if="!isViewMode">
                <el-icon><Download /></el-icon> 保存数据
              </el-button>
            </div>
          </div>

          <!-- 当类型不是堆垛机或非标堆垛机时显示提示信息 -->
          <div v-else class="empty-table-tips">
            <el-empty description="请选择设备类型为堆垛机或非标堆垛机以显示核价明细表" />
          </div>

          <div class="summary-section">
            <div class="summary-item">
              <span class="label">合计金额：</span>
              <span class="value">{{ formatPrice(totalAmount) }}</span>
            </div>
          </div>
        </el-card>
      </el-form>
    </el-card>

    <!-- 物料选择器弹窗，已经不需要 -->
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, FormInstance, ElLoading } from 'element-plus'
import { 
  getDevicePricingDetailApi, 
  addDevicePricingApi, 
  updateDevicePricingApi,
  calculateStackerPricingApi,
  getStackerPriceDataApi
} from '@/api/devicePricing/index'
import type { DevicePricingPlan, DeviceDetailItem } from '@/api/devicePricing/type'
import { Check, Back, Document, List, Download, RefreshRight } from '@element-plus/icons-vue'
import { getListApi as getDictListApi } from "@/api/sysDictData"
import { SysDictData } from "@/api/sysDictData/type"
import { getSimpleProject } from "@/api/project"
// 引入统一格式化工具
import { formatPrice } from '@/utils/formatter'

// 定义props接收路由传递的display参数
const props = defineProps({
  display: {
    type: String,
    default: 'false'
  }
})

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const id = computed(() => route.params.id ? Number(route.params.id) : undefined)
const title = computed(() => {
  if (isViewMode.value) {
    return '查看设备核价'
  } else if (id.value) {
    return '编辑设备核价'
  } else {
    return '新增设备核价'
  }
})

// 是否为查看模式
const isViewMode = computed(() => route.query.display === 'true' || props.display === 'true')

// 设备类别选项
const typeOptions = ref<SysDictData[]>([])

// 新增：货叉类型字典选项
const forkTypeOptions = ref<SysDictData[]>([])

// 新增各字段的 options
const commTypeOptions = ref<SysDictData[]>([])
const positionTypeOptions = ref<SysDictData[]>([])
const plcTypeOptions = ref<SysDictData[]>([])
const inverterTypeOptions = ref<SysDictData[]>([])
const photoelectricTypeOptions = ref<SysDictData[]>([])
const stationNumOptions = ref<SysDictData[]>([])
const slideLineInstallOptions = ref<SysDictData[]>([])
const motorEfficiencyOptions = ref<SysDictData[]>([])
const steelPriceOptions = ref<SysDictData[]>([])

// 新增分项单价表相关 options
const walkMotorOptions = ref<SysDictData[]>([])
const liftMotorOptions = ref<SysDictData[]>([])
const forkOptions = ref<SysDictData[]>([])
const envOptions = ref<SysDictData[]>([])
const railTypeOptions = ref<SysDictData[]>([])
const monitorOptions = ref<SysDictData[]>([])
const lidarOptions = ref<SysDictData[]>([])
const armorOptions = ref<SysDictData[]>([])
const dustOptions = ref<SysDictData[]>([])
const slideLineOptions = ref<SysDictData[]>([])

// 表单数据
const form = reactive<DevicePricingPlan>({
  id: undefined,
  projectId: undefined,
  projectName: '',
  type: '',
  sumPrice: 0,
  remark: '',
  detailItems: []
})

// 监听设备类型变化
watch(() => form.type, (newValue) => {
  if (newValue === '堆垛机' || newValue === '非标堆垛机') {
    // 当类型为堆垛机或非标堆垛机时，清空原来的明细项，避免提交时包含不需要的数据
    form.detailItems = []
    
    // 只有在新增模式下才计算初始总价，编辑模式下保持后端数据
    if (!id.value) {
      updateSummarizedData()
    }
  } else {
    // 清空表格数据
    form.detailItems = []
    form.sumPrice = 0
  }
})

// 优化：使用computed缓存表格数据切片
const specsTableData = computed(() => {
  const dividerIndex = stackerData.value.findIndex(item => item.name === '以下为分项单价')
  if (dividerIndex !== -1) {
    return stackerData.value.slice(0, dividerIndex)
  }
  return stackerData.value
})

const pricingTableData = computed(() => {
  const dividerIndex = stackerData.value.findIndex(item => item.name === '以下为分项单价')
  if (dividerIndex !== -1) {
    return stackerData.value.slice(dividerIndex + 1)
  }
  return []
})

// 表单校验规则
const rules = {
  projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
  type: [{ required: true, message: '请选择设备类别', trigger: 'change' }]
}

// 物料选择相关变量（不再需要，但保留变量避免引用错误）
const materialDialogVisible = ref(false)
const selectedMaterials = ref<any[]>([])

  // 合计金额
  const totalAmount = computed(() => form.sumPrice || 0)

  // 判断字段是否应该禁用编辑的逻辑
  const shouldDisableField = (fieldName: string) => {
    // 查看模式下都禁用
    if (isViewMode.value) return true
    
    // 非标堆垛机：所有字段都可以编辑
    if (form.type === '非标堆垛机') {
      // 处理价格和备注字段
      if (fieldName.endsWith('_price') || fieldName.endsWith('_remark')) {
        const baseFieldName = fieldName.replace(/_price$|_remark$/, '')
        const restrictedFields = [
          '提升行程', '行走轮直径', '卷筒直径', '钢丝绳直径', '卷筒形式', '载货台类型',
          '立柱规格', '载货台重量', '立柱重量', '上下横梁重量', '附件重量', '提升总重',
          '行走总重过程', '行走总重', '需求转速', '需求扭矩', '需求功率',
          '需求转速2', '需求扭矩2', '需求功率2', '电机型号', '电机型号2',
          '输出功率2', '额定转速2', '额定扭矩2', '输出功率', '额定转速', '额定扭矩',
          '减速机型号', '减速机型号2',  '基频频率2', '电机功率段2',
          '基频频率', '电机功率段', '堆垛机电控',
         
        ]
        return restrictedFields.includes(baseFieldName)
      }
      
      // 处理普通字段
      const restrictedFields = [
        '提升行程', '行走轮直径', '卷筒直径', '钢丝绳直径', '卷筒形式', '载货台类型',
        '立柱规格', '载货台重量', '立柱重量', '上下横梁重量', '附件重量', '提升总重',
        '行走总重过程', '行走总重', '需求转速', '需求扭矩', '需求功率',
        '需求转速2', '需求扭矩2', '需求功率2', '电机型号', '电机型号2',
        '输出功率2', '额定转速2', '额定扭矩2', '输出功率', '额定转速', '额定扭矩',
        '减速机型号', '减速机型号2', '基频频率2', '电机功率段2',
        '基频频率', '电机功率段', '堆垛机电控',

      ]
      return restrictedFields.includes(fieldName)
    }
    
    // 标准堆垛机：某些计算字段和系统字段不允许编辑
    if (form.type === '堆垛机') {
      // 处理价格和备注字段
      if (fieldName.endsWith('_price') || fieldName.endsWith('_remark')) {
        const baseFieldName = fieldName.replace(/_price$|_remark$/, '')
        const restrictedFields = [
          '提升行程', '行走轮直径', '卷筒直径', '钢丝绳直径', '卷筒形式', '载货台类型',
          '立柱规格', '载货台重量', '立柱重量', '上下横梁重量', '附件重量', '提升总重',
          '行走总重过程', '行走总重', '需求转速', '需求扭矩', '需求功率',
          '需求转速2', '需求扭矩2', '需求功率2', '电机型号', '电机型号2',
          '输出功率2', '额定转速2', '额定扭矩2', '输出功率', '额定转速', '额定扭矩',
          '减速机型号', '减速机型号2', '提升电机', '行走电机', '基频频率2', '电机功率段2',
          '基频频率', '电机功率段', '堆垛机电控',
          '机械本体', '电控', '机械安装调试', '电控安装调试',
          '其他非标', '单台', '合计', '滑触线护板', '运输'
        ]
        return restrictedFields.includes(baseFieldName)
      }
      
      // 处理普通字段
      const restrictedFields = [
        '提升行程', '行走轮直径', '卷筒直径', '钢丝绳直径', '卷筒形式', '载货台类型',
        '立柱规格', '载货台重量', '立柱重量', '上下横梁重量', '附件重量', '提升总重',
        '行走总重过程', '行走总重', '需求转速', '需求扭矩', '需求功率',
        '需求转速2', '需求扭矩2', '需求功率2', '电机型号', '电机型号2',
        '输出功率2', '额定转速2', '额定扭矩2', '输出功率', '额定转速', '额定扭矩',
        '减速机型号', '减速机型号2', '提升电机', '行走电机', '基频频率2', '电机功率段2',
        '基频频率', '电机功率段', '堆垛机电控',
        '机械本体', '电控', '机械安装调试', '电控安装调试',
        '其他非标', '单台', '合计', '滑触线护板', '运输'
      ]
      return restrictedFields.includes(fieldName)
    }
    
    return false
  }

// 使用统一的格式化工具，删除本地formatPrice函数

// 定义项目接口类型
interface Project {
  id: number;
  name: string;
}

// 项目列表
const projectList = ref<Project[]>([])

// 字典数据加载状态
const dictLoadingStates = reactive<Record<string, boolean>>({
  typeOptions: false,
  forkTypeOptions: false,
  commTypeOptions: false,
  positionTypeOptions: false,
  plcTypeOptions: false,
  inverterTypeOptions: false,
  photoelectricTypeOptions: false,
  stationNumOptions: false,
  slideLineInstallOptions: false,
  motorEfficiencyOptions: false,
  steelPriceOptions: false,
  walkMotorOptions: false,
  liftMotorOptions: false,
  forkOptions: false,
  envOptions: false,
  railTypeOptions: false,
  monitorOptions: false,
  lidarOptions: false,
  armorOptions: false,
  dustOptions: false,
  slideLineOptions: false
})

// 优化：批量加载字典数据函数
const loadAllDictOptions = async () => {
  const dictTypes = [
    { type: 'forkType', target: forkTypeOptions },
    { type: 'commType', target: commTypeOptions },
    { type: 'positionType', target: positionTypeOptions },
    { type: 'plcType', target: plcTypeOptions },
    { type: 'inverterType', target: inverterTypeOptions },
    { type: 'photoelectricType', target: photoelectricTypeOptions },
    { type: 'stationNumType', target: stationNumOptions },
    { type: 'slideLineInstallType', target: slideLineInstallOptions },
    { type: 'motorEfficiencyType', target: motorEfficiencyOptions },
    { type: 'steelPriceType', target: steelPriceOptions },
    { type: 'walkMotorType', target: walkMotorOptions },
    { type: 'liftMotorType', target: liftMotorOptions },
    { type: 'forkType2', target: forkOptions },
    { type: 'envType', target: envOptions },
    { type: 'railType', target: railTypeOptions },
    { type: 'monitorType', target: monitorOptions },
    { type: 'lidarType', target: lidarOptions },
    { type: 'armorType', target: armorOptions },
    { type: 'dustType', target: dustOptions },
    { type: 'slideLineType', target: slideLineOptions }
  ]

  // 并行加载所有字典数据
  const promises = dictTypes.map(async ({ type, target }) => {
    try {
      const data = await getDictOptions(type, target)
      return { type, success: true }
    } catch (error) {
      console.error(`加载字典 ${type} 失败:`, error)
      return { type, success: false, error }
    }
  })

  // 加载货叉类型选项
  promises.push(getForkTypeOptions().then(() => ({ type: 'forkType', success: true })).catch(error => ({ type: 'forkType', success: false, error })))

  const results = await Promise.all(promises)
  const failedTypes = results.filter(r => !r.success)
  if (failedTypes.length > 0) {
    console.warn('部分字典数据加载失败:', failedTypes)
  }
}

// 优化：堆垛机价格数据加载（增加缓存机制）
let stackerDataCache: any[] | null = null
const loadStackerPricingData = async () => {
  // 如果已有缓存数据，直接使用
  if (stackerDataCache && stackerDataCache.length > 0) {
    stackerData.value = [...stackerDataCache]
    return
  }

  try {
    const res = await getStackerPriceDataApi()
    if (res && res.data) {
      stackerDataCache = res.data // 缓存数据
      stackerData.value = [...res.data]
    }
  } catch (error) {
    console.error('获取堆垛机价格数据失败:', error)
    ElMessage.error('获取堆垛机价格数据失败')
  }
}

// 获取项目列表
const getProjectList = async () => {
  try {
    const res = await getSimpleProject()
    if (res && res.data) {
      projectList.value = res.data
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}

// 堆垛机固定数据
const stackerData = ref([
  { name: '堆垛机数量', unit: '台', defaultValue: '1', price: 0, precision: 0,  remark: '' },
  { name: '货架高度', unit: 'm', defaultValue: '12', price: 0, precision: 0,  remark: '卷筒容绳量:' },
  { name: '提升行程', unit: 'm', defaultValue: '9.8', price: 0, precision: 2,  remark: '' },
  { name: '巷道长度', unit: 'm', defaultValue: '100', price: 0, precision: 0,  remark: '' },
  { name: '巷道宽度', unit: 'mm', defaultValue: '1550', price: 0, precision: 0,  remark: '' },
  { name: '长L', unit: 'm', defaultValue: '1.3', price: 0, precision: 0,  remark: '≤3.5m(进叉)' },
  { name: '宽W', unit: 'm', defaultValue: '1.3', price: 0, precision: 0,  remark: '≤2m' },
  { name: '高H', unit: 'm', defaultValue: '1.2', price: 0, precision: 0,  remark: '≤2.5' },
  { name: '货物重量', unit: 'kg', defaultValue: '500', price: 0, precision: 0,  remark: '单伸:≤2500kg;双伸:≤2000kg' },
  { name: '货叉类型', unit: '/', defaultValue: '双指叉单伸', price: 0, precision: 0,  remark: '多叉不适用' },
  { name: '货叉重量', unit: 'kg', defaultValue: '300', price: 0, precision: 0,  remark: '建议手动输入' },
  { name: '满载行走速度', unit: 'm/min', defaultValue: '120', price: 0, precision: 0,  remark: '空载最大超频8%' },
  { name: '满载行走加速度', unit: 'm/s2', defaultValue: '0.3', price: 0, precision: 0,  remark: '空、满载一样' },
  { name: '行走轮直径', unit: 'mm', defaultValue: '315', price: 0, precision: 0, remark: '' },
  { name: '满载提升速度', unit: 'm/min', defaultValue: '30', price: 0, precision: 0,  remark: '空载最大超频15%' },
  { name: '满载提升加速度', unit: 'm/s2', defaultValue: '0.3', price: 0, precision: 0,  remark: '空载0.5' },
  { name: '卷筒直径', unit: 'mm', defaultValue: '298', price: 0, precision: 0,  remark: '' },
  { name: '卷筒形式', unit: '/', defaultValue: '无动滑轮', price: 0, precision: 0, remark: '' },
  { name: '载货台类型', unit: '/', defaultValue: 'YFM018', price: 0, precision: 0, remark: '' },
  { name: '立柱规格', unit: 'mm', defaultValue: '300×300×8', price: 0, precision: 0,  remark: '' },
  { name: '载货台重量', unit: 'kg', defaultValue: '772.4', price: 0, precision: 0, remark: '' },
  { name: '立柱重量', unit: 'kg', defaultValue: '2003.72928', price: 0, precision: 0, remark: '' },
  { name: '上下横梁重量', unit: 'kg', defaultValue: '1147.88', price: 0, precision: 0, remark: '' },
  { name: '附件重量', unit: 'kg', defaultValue: '1710', price: 0, precision: 0, remark: '' },
  { name: '提升总重', unit: 'kg', defaultValue: '1672.4', price: 0, precision: 0, remark: '' },
  { name: '行走总重过程', unit: 'kg', defaultValue: '6534.00928', price: 0, precision: 0, remark: '' },
  { name: '行走总重', unit: 'kg', defaultValue: '6534.00928', price: 0, precision: 0, remark: '' },
  { name: '钢丝绳直径', unit: 'mm', defaultValue: '12', price: 0, precision: 0,  remark: '' },
  { name: '需求转速', unit: 'r/min', defaultValue: '121.3224143', price: 0, precision: 0, remark: '' },
  { name: '需求扭矩', unit: 'Nm', defaultValue: '457.3806496', price: 0, precision: 0, remark: '' },
  { name: '需求功率', unit: 'kw', defaultValue: '5.810526144', price: 0, precision: 0, remark: '' },
  { name: '基频频率', unit: 'Hz', defaultValue: '87', price: 0, precision: 0,  remark: '可以不要，默认87HZ' },
  { name: '电机功率段', unit: 'kw', defaultValue: '4', price: 0, precision: 0,  remark: '' },
  { name: '电机型号', unit: '/', defaultValue: 'DR2S 100L4', price: 0, precision: 0, remark: '' },
  { name: '输出功率', unit: 'kw', defaultValue: '6.96', price: 0, precision: 0, remark: '可以不要' },
  { name: '额定转速', unit: 'r/min', defaultValue: '1445', price: 0, precision: 0, remark: '可以不要' },
  { name: '额定扭矩', unit: 'Nm', defaultValue: '26.5', price: 0, precision: 0, remark: '可以不要' },
  { name: '减速机型号', unit: '/', defaultValue: 'KA67', price: 0, precision: 0, remark: '' },
  { name: '行走电机', unit: '个', defaultValue: 'KA67DR2S 100L4', price: 0, precision: 0, remark: 'SEW' },
  { name: '需求转速2', unit: 'r/min', defaultValue: '121.3224143', price: 0, precision: 0, remark: '' },
  { name: '需求扭矩2', unit: 'Nm', defaultValue: '457.3806496', price: 0, precision: 0, remark: '' },
  { name: '需求功率2', unit: 'kw', defaultValue: '5.810526144', price: 0, precision: 0, remark: '' },
  { name: '基频频率2', unit: 'Hz', defaultValue: '87', price: 0, precision: 0, remark: '可以不要，默认87HZ' },
  { name: '电机功率段2', unit: 'kw', defaultValue: '7.5', price: 0, precision: 0, remark: '' },
  { name: '电机型号2', unit: '/', defaultValue: 'DR2S 100L4', price: 0, precision: 0, remark: '' },
  { name: '输出功率2', unit: 'kw', defaultValue: '6.96', price: 0, precision: 0, remark: '可以不要' },
  { name: '额定转速2', unit: 'r/min', defaultValue: '1445', price: 0, precision: 0, remark: '可以不要' },
  { name: '额定扭矩2', unit: 'Nm', defaultValue: '26.5', price: 0, precision: 0, remark: '可以不要' },
  { name: '减速机型号2', unit: '/', defaultValue: 'KA67', price: 0, precision: 0, remark: '' },
  { name: '提升电机', unit: '个', defaultValue: 'K97DR2S 132S4', price: 0, precision: 0, remark: 'SEW' },
  { name: '通讯方式', unit: '套', defaultValue: 'SICK光通讯', price: 0, precision: 0, remark: '' },
  { name: '定位方式', unit: '套', defaultValue: 'SICK激光', price: 0, precision: 0, remark: '激光范围：≤190m' },
  { name: 'PLC', unit: '套', defaultValue: '西门子1200', price: 0, precision: 0, remark: '' },
  { name: '变频器', unit: '套', defaultValue: '西门子', price: 0, precision: 0, remark: '' },
  { name: '光电开关', unit: '套', defaultValue: 'SICK光电', price: 0, precision: 0, remark: '' },
  { name: '堆垛机电控', unit: '套', defaultValue: '', price: 0, precision: 0, remark: '' },
  { name: '地面站数量', unit: '台', defaultValue: '有', price: 0, precision: 0, remark: '' },
  { name: '滑触线安装方式', unit: '/', defaultValue: '底部安装', price: 0, precision: 0, remark: '' },
  { name: '能效等级要求', unit: '/', defaultValue: '无', price: 0, precision: 0, remark: '' },
  { name: '当前钢材价格', unit: '元', defaultValue: '3500-4000', price: 0, precision: 0, remark: '1' },
  
  { name: '以下为分项单价', unit: '', defaultValue: '', price: 0, precision: 0, remark: '' },
  { name: '机械本体', unit: '套', defaultValue: '自制', price: 0, precision: 0, remark: '' },
  { name: '行走电机', unit: '套', defaultValue: 'SEW', price: 0, precision: 0, remark: '' },
  { name: '提升电机', unit: '套', defaultValue: 'SEW', price: 0, precision: 0, remark: '' },
  { name: '货叉', unit: '套', defaultValue: '米亚斯', price: 0, precision: 0, remark: '' },
  { name: '电控', unit: '套', defaultValue: '自制', price: 0, precision: 0, remark: '' },
  { name: '机械安装调试', unit: '套', defaultValue: '', price: 0, precision: 0, remark: '第一台12000元，之后10000元/台.只包含调试费' },
  { name: '电控安装调试', unit: '套', defaultValue: '', price: 0, precision: 0, remark: '第一台7000元，之后3500元/台.只包含调试费' },
  { name: '使用环境', unit: '套', defaultValue: '常温', price: 0, precision: 0, remark: '机械*1.2，电控*1.3' },
  { name: '轨道类型', unit: '套', defaultValue: '直轨', price: 0, precision: 0, remark: '' },
  { name: '单机监控', unit: '套', defaultValue: '有', price: 0, precision: 0, remark: '' },
  { name: '巷道激光雷达', unit: '套', defaultValue: '无', price: 0, precision: 0, remark: '' },
  { name: '铠甲/灭火器', unit: '套', defaultValue: '无', price: 0, precision: 0, remark: '' },
  { name: '金属粉尘管控', unit: '套', defaultValue: '无', price: 0, precision: 0, remark: '' },
  { name: '其他非标', unit: '套', defaultValue: '', price: 0, precision: 0, remark: '' },
  { name: '单台', unit: '元', defaultValue: '', price: 0, precision: 1, remark: '' },
  { name: '合计', unit: '元', defaultValue: '', price: 0, precision: 1, remark: '' },
  { name: '条码带', unit: '米', defaultValue: '', price: 0, precision: 0, remark: '' },
  { name: '滑触线', unit: 'm', defaultValue: '瑞能', price: 0, precision: 0, remark: '' },
  { name: '滑触线护板', unit: 'm', defaultValue: '', price: 0, precision: 0, remark: '' },
  { name: '运输', unit: '车', defaultValue: '17.5米', price: 0, precision: 0, remark: '' }
])

// 获取货叉的有效价格（优先使用备注价格，否则使用原价格）
const getEffectiveForkPrice = () => {
  const forkItem = stackerData.value.find(item => item.name === '货叉')
  if (!forkItem) return 0
  
  const remarkPrice = getForkPriceFromRemark()
  return remarkPrice > 0 ? remarkPrice : (forkItem.price || 0)
}

// 从货叉备注获取价格（用于计算时）
const getForkPriceFromRemark = () => {
  const forkItem = stackerData.value.find(item => item.name === '货叉')
  if (!forkItem || !forkItem.remark) return 0
  
  // 尝试将备注转换为数字
  const remarkValue = forkItem.remark
  if (!isNaN(parseFloat(remarkValue)) && isFinite(parseFloat(remarkValue))) {
    return parseFloat(remarkValue)
  }
  
  return 0
}

// 处理货叉备注变化
const onForkRemarkChange = () => {
  // 找到货叉行
  const forkItem = stackerData.value.find(item => item.name === '货叉')
  if (!forkItem) return
  
  // 从备注中获取新的货叉价格
  const newForkPrice = getForkPriceFromRemark()
  
  if (newForkPrice > 0) {
    // 记录原来的价格用于提示
    const originalForkPrice = forkItem.price || 0
    
    // 提示信息
    ElMessage.success(`货叉将使用备注价格：${newForkPrice}元进行计算（原价格${originalForkPrice}元保持不变）`)
  } else {
    // 如果备注为空或无效，提示将使用原价格计算
    if (forkItem.remark === '' || forkItem.remark === undefined) {
      ElMessage.info('货叉备注已清空，将使用原价格进行计算')
    }
  }
  
  // 重新计算总价，这样会优先使用备注价格
  updateSummarizedData()
}

// 更新汇总数据
const updateSummarizedData = () => {
  // 从表格中找到相关项目
  const totalItem = stackerData.value.find(item => item.name === '合计')
  const barCodeItem = stackerData.value.find(item => item.name === '条码带')
  const slidingContactItem = stackerData.value.find(item => item.name === '滑触线')
  const slidingContactGuardItem = stackerData.value.find(item => item.name === '滑触线护板')
  const forkItem = stackerData.value.find(item => item.name === '货叉')
  const quantityItem = stackerData.value.find(item => item.name === '堆垛机数量')
  const singleMachineItem = stackerData.value.find(item => item.name === '单台')
  
  const quantity = quantityItem ? parseFloat(quantityItem.defaultValue) || 1 : 1
  
  // 第一步：重新计算"单台"价格（包含货叉的有效价格）
  if (singleMachineItem) {
    let singleMachinePrice = 0
    
    // 计算单台价格的所有组成部分
    const components = [
      '机械本体', '行走电机', '提升电机', '电控', '机械安装调试', 
      '电控安装调试', '轨道类型', '单机监控', '巷道激光雷达', 
      '铠甲/灭火器', '金属粉尘管控', '其他非标'
    ]
    
    components.forEach(componentName => {
      const componentItem = stackerData.value.find(item => item.name === componentName)
      if (componentItem && typeof componentItem.price === 'number') {
        singleMachinePrice += componentItem.price
      }
    })
    
    // 特殊处理货叉：使用有效价格（备注价格优先）
    const effectiveForkPrice = getEffectiveForkPrice()
    singleMachinePrice += effectiveForkPrice
    
    // 更新单台价格
    singleMachineItem.price = singleMachinePrice
    console.log('重新计算单台价格:', singleMachinePrice, '(包含货叉有效价格:', effectiveForkPrice, ')')
    
    // 第二步：重新计算"合计"价格：单台价格 × 堆垛机数量
    if (totalItem) {
      totalItem.price = singleMachinePrice * quantity
      console.log('重新计算合计价格:', totalItem.price, '= 单台价格', singleMachinePrice, '× 数量', quantity)
    }
  }
  
  // 第三步：计算最终的 form.sumPrice（合计 + 其他费用项目）
  let finalTotalPrice = 0
  
  if (totalItem && typeof totalItem.price === 'number') {
    // 使用重新计算后的合计价格
    finalTotalPrice = totalItem.price
  } else {
    // 如果没有找到合计字段，则直接计算所有项的总和
    stackerData.value.forEach(item => {
      if (typeof item.price === 'number') {
        // 对于货叉，使用有效价格
        if (item.name === '货叉') {
          const effectiveForkPrice = getEffectiveForkPrice()
          finalTotalPrice += effectiveForkPrice * quantity
        } else {
          finalTotalPrice += item.price
        }
      }
    })
  }
  
  // 加上额外费用项目
  let additionalCost = 0
  
  if (barCodeItem && typeof barCodeItem.price === 'number') {
    additionalCost += barCodeItem.price
  }
  
  if (slidingContactItem && typeof slidingContactItem.price === 'number') {
    additionalCost += slidingContactItem.price
  }
  
  if (slidingContactGuardItem && typeof slidingContactGuardItem.price === 'number') {
    additionalCost += slidingContactGuardItem.price
  }
  
  form.sumPrice = finalTotalPrice + additionalCost
  console.log('最终总价:', form.sumPrice, '= 合计价格', finalTotalPrice, '+ 额外费用', additionalCost)
}

// 获取设备核价详情 - 优化版本
const getDevicePricingDetail = async () => {
  if (!id.value) return
  
  const loading = ElLoading.service({
    text: '正在加载设备核价详情...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const res = await getDevicePricingDetailApi(id.value)
    if (res && res.data) {
      const data = res.data
    
      // 基本信息赋值
      Object.assign(form, {
        id: data.id,
        projectId: data.projectId,
        projectName: data.projectName,
        type: data.type,
        sumPrice: data.sumPrice,
        remark: data.remark
      })
      
      // 如果是堆垛机或非标堆垛机类型，需要解析stackerData字段
      if ((data.type === '堆垛机' || data.type === '非标堆垛机') && data.stackerData) {
        try {
          // 解析JSON字符串
          const parsedData = JSON.parse(data.stackerData)
          if (Array.isArray(parsedData) && parsedData.length > 0) {
            // 使用nextTick优化DOM更新
            await nextTick()
            stackerData.value = parsedData
            
            // 检查货叉是否有自定义价格标识，如果有则恢复到备注中
            const forkItem = stackerData.value.find(item => item.name === '货叉')
            if (forkItem && (forkItem as any).useCustomPrice && (forkItem as any).customPrice) {
              // 将自定义价格恢复到备注字段中
              forkItem.remark = String((forkItem as any).customPrice)
              console.log('恢复货叉自定义价格到备注:', (forkItem as any).customPrice)
              
              // 清除临时标识字段
              delete (forkItem as any).customPrice
              delete (forkItem as any).useCustomPrice
            }
            
            // 数据加载完成后，如果后端返回的sumPrice有效，则使用后端数据
            // 否则重新计算总价
            if (data.sumPrice && data.sumPrice > 0) {
              // 保持后端返回的总价不变
              form.sumPrice = data.sumPrice
            } else {
              // 如果后端总价为0或无效，则重新计算
              updateSummarizedData()
            }
          }
        } catch (e) {
          console.error('解析堆垛机数据失败:', e)
          ElMessage.error('解析堆垛机数据失败')
        }
      } 
      // 兼容旧数据：如果没有stackerData但有detailItems，尝试从detailItems中恢复数据
      else if ((data.type === '堆垛机' || data.type === '非标堆垛机') && data.detailItems && data.detailItems.length > 0) {
        // 遍历detailItems，更新stackerData中对应的值
        data.detailItems.forEach((item: any) => {
          const stackerItem = stackerData.value.find(sItem => sItem.name === item.materialCode)
          if (stackerItem) {
            stackerItem.price = item.quantity || 0
            stackerItem.defaultValue = item.specification || stackerItem.defaultValue
            stackerItem.remark = item.remark || stackerItem.remark
            if (item.nonStandard === '1') {
              (stackerItem as any).color = 'red'
            }
          }
        })
        
        // 数据恢复完成后，如果后端返回的sumPrice有效，则使用后端数据
        if (data.sumPrice && data.sumPrice > 0) {
          form.sumPrice = data.sumPrice
        } else {
          updateSummarizedData()
        }
      }
      
      // 确保在数据加载完成后，totalAmount能正确显示
      await nextTick()
      
      // 强制触发响应式更新
      if (data.sumPrice && data.sumPrice > 0) {
        // 使用临时变量强制触发响应式更新
        const tempSumPrice = form.sumPrice
        form.sumPrice = 0
        await nextTick()
        form.sumPrice = tempSumPrice
      }
    }
  } catch (error) {
    console.error('获取设备核价详情失败:', error)
    ElMessage.error('获取设备核价详情失败')
  } finally {
    loading.close()
  }
}

// 获取设备类别字典
const getTypeOptions = async () => {
  try {
    const res = await getDictListApi({
      dictType: 'deviceType',
      dictLabel: "",
      status: undefined,
      page: 0,
      limit: 100
    })
    if (res && res.data) {
      typeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取设备类别列表失败:', error)
  }
}

// 获取货叉类型字典
const getForkTypeOptions = async () => {
  try {
    const res = await getDictListApi({
      dictType: 'forkType',
      dictLabel: '',
      status: undefined,
      page: 0,
      limit: 100
    })
    if (res && res.data) {
      forkTypeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取货叉类型字典失败:', error)
  }
}

// 批量获取方法
type DictTarget = typeof commTypeOptions
const getDictOptions = async (dictType: string, target: DictTarget) => {
  try {
    const res = await getDictListApi({
      dictType,
      dictLabel: '',
      status: undefined,
      page: 0,
      limit: 100
    })
    if (res && res.data) {
      target.value = res.data.list || []
    }
  } catch (error) {
    console.error(`获取${dictType}字典失败:`, error)
  }
}

// 更新计算的加载状态
const calculateLoading = ref(false)

// 保存表单的加载状态
const saveLoading = ref(false)

// 发送数据到后端计算价格
const calculatePricing = async () => {
  if (!form.type || (form.type !== '堆垛机' && form.type !== '非标堆垛机')) {
    ElMessage.error('目前只支持堆垛机和非标堆垛机类型的设备核价')
    return
  }
  
  calculateLoading.value = true
  try {
    // 在计算前，先更新货叉的价格（从备注中获取有效价格）
    const forkItem = stackerData.value.find(item => item.name === '货叉')
    let originalForkPrice = 0
    let forkRemarkPrice = 0
    
    if (forkItem) {
      originalForkPrice = forkItem.price || 0
      forkRemarkPrice = getForkPriceFromRemark()
      
      // 临时设置货叉价格为有效价格，传递给后端
      if (forkRemarkPrice > 0) {
        forkItem.price = forkRemarkPrice
        console.log('使用货叉备注价格进行计算:', forkRemarkPrice)
      }
    }
    
    // 准备请求数据
    const requestData = {
      specsData: specsTableData.value,
      pricingData: pricingTableData.value
    }
    
    // 调用后端计算接口
    const res = await calculateStackerPricingApi(requestData)
    
    if (res && res.data) {
      // 解构返回的数据
      const { specsData, pricingData } = res.data
      
      // 更新规格参数表数据
      if (specsData && Array.isArray(specsData)) {
        const dividerIndex = stackerData.value.findIndex(item => item.name === '以下为分项单价')
        if (dividerIndex !== -1) {
          // 更新规格参数表部分
          stackerData.value.splice(0, dividerIndex, ...specsData)
        }
      }
      
      // 更新分项单价表数据
      if (pricingData && Array.isArray(pricingData)) {
        const dividerIndex = stackerData.value.findIndex(item => item.name === '以下为分项单价')
        if (dividerIndex !== -1) {
          // 更新分项单价表部分（保留分隔行）
          stackerData.value.splice(dividerIndex + 1, stackerData.value.length - dividerIndex - 1, ...pricingData)
        }
      }
      
      // 恢复货叉的原始价格（保持留痕），但在计算时仍使用备注价格
      if (forkItem && forkRemarkPrice > 0) {
        const updatedForkItem = stackerData.value.find(item => item.name === '货叉')
        if (updatedForkItem) {
          // 恢复原始价格用于显示（留痕）
          updatedForkItem.price = originalForkPrice
          console.log('恢复货叉原始价格用于显示:', originalForkPrice)
          console.log('但计算时仍使用备注价格:', forkRemarkPrice)
        }
      }
      
      // 重新计算总价（会自动使用货叉的有效价格）
      updateSummarizedData()
      
      ElMessage.success('计算完成')
    }
  } catch (error) {
    console.error('计算失败:', error)
    ElMessage.error('计算失败，请稍后重试')
  } finally {
    calculateLoading.value = false
  }
}

// 保存表格数据 (重命名为 saveTableData)
const saveTableData = async () => {
  if (!form.projectId) {
    ElMessage.error('请选择项目')
    return
  }
  
  if (!form.type || (form.type !== '堆垛机' && form.type !== '非标堆垛机')) {
    ElMessage.error('目前只支持堆垛机和非标堆垛机类型的设备核价')
    return
  }
  
  // 计算总价（会自动使用货叉的有效价格）
  updateSummarizedData()
  
  // 创建一个深拷贝，用于保存时包含货叉的有效价格信息
  const stackerDataForSave: any[] = JSON.parse(JSON.stringify(stackerData.value))
  
  // 确保保存的数据中货叉使用有效价格
  const forkItemForSave = stackerDataForSave.find((item: any) => item.name === '货叉')
  if (forkItemForSave) {
    const effectiveForkPrice = getEffectiveForkPrice()
    const remarkPrice = getForkPriceFromRemark()
    
    // 如果有备注价格，在保存的数据中添加标识
    if (remarkPrice > 0) {
      forkItemForSave.customPrice = remarkPrice  // 添加自定义价格字段
      forkItemForSave.useCustomPrice = true      // 添加使用自定义价格标识
      console.log('保存数据时，货叉使用自定义价格:', remarkPrice)
    }
  }
  
  // 将堆垛机数据序列化为JSON字符串
  const stackerDataString = JSON.stringify(stackerDataForSave)
  
  saveLoading.value = true
  try {
    // 构建提交数据
    const formData = {
      ...form,
      projectId: form.projectId,
      type: form.type,
      stackerData: stackerDataString,  // 存储序列化的堆垛机数据
      detailItems: []  // 保持空数组，不再使用旧的明细结构
    }
    
    if (id.value) {
      // 更新
      await updateDevicePricingApi({
        ...formData,
        id: id.value
      })
      ElMessage.success('保存成功')
    } else {
      // 新增
      const res = await addDevicePricingApi(formData)
      if (res && res.data) {
        // 如果是新增成功，设置ID以便后续操作可以使用
        form.id = Number(res.data)
      }
      ElMessage.success('添加成功')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  } finally {
    saveLoading.value = false
  }
}

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    
    if (!form.projectId) {
      ElMessage.error('请选择项目')
      return
    }
    
    if (!form.type) {
      ElMessage.error('请选择设备类型')
      return
    }
    
    // 验证是否为堆垛机或非标堆垛机类型
    if (form.type !== '堆垛机' && form.type !== '非标堆垛机') {
      ElMessage.error('目前只支持堆垛机和非标堆垛机类型的设备核价')
      return
    }
    
    // 计算总价（会自动使用货叉的有效价格）
    updateSummarizedData()
    
    // 创建一个深拷贝，用于提交时包含货叉的有效价格信息
    const stackerDataForSubmit: any[] = JSON.parse(JSON.stringify(stackerData.value))
    
    // 确保提交的数据中货叉使用有效价格
    const forkItemForSubmit = stackerDataForSubmit.find((item: any) => item.name === '货叉')
    if (forkItemForSubmit) {
      const effectiveForkPrice = getEffectiveForkPrice()
      const remarkPrice = getForkPriceFromRemark()
      
      // 如果有备注价格，在提交的数据中添加标识
      if (remarkPrice > 0) {
        forkItemForSubmit.customPrice = remarkPrice  // 添加自定义价格字段
        forkItemForSubmit.useCustomPrice = true      // 添加使用自定义价格标识
        console.log('提交数据时，货叉使用自定义价格:', remarkPrice)
      }
    }
    
    // 收集用户修改后的数据，用于后续数据更新或历史记录
    const userModifiedData: {
      defaultValues: Record<string, string | number>;
      prices: Record<string, number>;
    } = {
      defaultValues: {},
      prices: {}
    }
    
    // 遍历堆垛机数据，收集用户修改的值（使用有效价格）
    stackerDataForSubmit.forEach((item: any) => {
      // 收集数值(满载)
      userModifiedData.defaultValues[item.name] = item.defaultValue
      
      // 收集价格(元) - 对于货叉使用有效价格
      if (typeof item.price === 'number') {
        if (item.name === '货叉') {
          userModifiedData.prices[item.name] = getEffectiveForkPrice()
        } else {
          userModifiedData.prices[item.name] = item.price
        }
      }
    })
    
    // 将堆垛机数据序列化为JSON字符串
    const stackerDataString = JSON.stringify(stackerDataForSubmit)
    
    submitLoading.value = true
    try {
      // 构建提交数据
      const formData = {
        ...form,
        projectId: form.projectId,
        type: form.type,
        stackerData: stackerDataString,  // 新增字段，存储序列化的堆垛机数据
        userModifiedData: JSON.stringify(userModifiedData),  // 存储用户修改的数据
        detailItems: []  // 保持空数组，不再使用旧的明细结构
      }
      
      if (id.value) {
        // 更新
        await updateDevicePricingApi({
          ...formData,
          id: id.value
        })
        ElMessage.success('更新成功')
      } else {
        // 新增
        await addDevicePricingApi(formData)
        ElMessage.success('添加成功')
      }
      goBack()
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请稍后重试')
    } finally {
      submitLoading.value = false
    }
  })
}

// 返回列表页
const goBack = () => {
  router.push('/devicePricing')
}

onMounted(async () => {

    // 如果是编辑模式，加载详情数据
    if (id.value) {
    await getDevicePricingDetail()
  }

  console.log('onMounted - form.sumPrice:', form.sumPrice)
  console.log('onMounted - totalAmount:', totalAmount.value)

  // 优化：并行加载基础数据和字典数据
  const basicDataPromises = [
    getTypeOptions(),
    getProjectList(),
    loadAllDictOptions()
  ]
  
  // 等待基础数据加载完成
  await Promise.all(basicDataPromises)
  
  // 确保在基础数据加载完成后，再次检查totalAmount
  console.log('基础数据加载完成 - form.sumPrice:', form.sumPrice)
  console.log('基础数据加载完成 - totalAmount:', totalAmount.value)

})
</script>

<style scoped lang="scss">
.device-pricing-form {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  
  .box-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 18px;
        font-weight: 600;
      }
      
      .buttons {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .base-info-card,
  .device-details-card {
    margin-bottom: 20px;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    
    .form-section-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      color: #409eff;
      
      .action-buttons {
        margin-left: auto;
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .empty-table-tips {
    padding: 40px 0;
    background-color: #f8f8f8;
    border-radius: 4px;
    margin-bottom: 20px;
  }
  
  .device-details-table {
    width: 100%;
    margin-bottom: 20px;
  }
  
  .table-title {
    font-size: 16px;
    margin: 20px 0 10px;
    padding-left: 10px;
    border-left: 3px solid #409eff;
    font-weight: 600;
  }
  
  .pricing-title {
    border-left: 3px solid #f56c6c;
    margin-top: 30px;
  }
  
  .pricing-table {
    margin-bottom: 30px;
  }
  
  .table-actions {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
  }
  
  .summary-section {
    display: flex;
    justify-content: flex-end;
    padding: 16px 0;
    font-size: 16px;
    
    .summary-item {
      display: flex;
      align-items: center;
      gap: 10px;
      
      .label {
        font-weight: 600;
      }
      
      .value {
        font-size: 18px;
        color: #f56c6c;
        font-weight: 700;
      }
    }
  }
}

.full-width {
  width: 100%;
}

.material-dialog {
  :deep(.el-dialog) {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    
    .el-dialog__header {
      margin: 0;
      padding: 0;
    }
    
    .el-dialog__body {
      padding: 0;
    }
    
    .el-dialog__footer {
      padding: 12px 20px;
      border-top: 1px solid #ebeef5;
    }
  }

  .material-dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: linear-gradient(135deg, #409eff, #1677ff);
    color: white;
    
    .dialog-title {
      display: flex;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
      
      .dialog-icon {
        margin-right: 10px;
        font-size: 20px;
      }
    }
    
    .dialog-close {
      background: rgba(255, 255, 255, 0.2);
      border: none;
      
      &:hover {
        background: rgba(255, 255, 255, 0.3);
        transform: rotate(90deg);
        transition: all 0.3s;
      }
    }
  }
  
  .material-dialog-body {
    padding: 20px;
    max-height: 65vh;
    overflow-y: auto;
  }
  
  .material-dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    
    .el-button {
      padding: 9px 20px;
      
      &.el-button--primary {
        background: linear-gradient(135deg, #409eff, #1677ff);
        border: none;
        transition: all 0.3s;
        
        &:hover {
          opacity: 0.9;
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
        }
      }
    }
  }
}
</style>